package com.spider.admin.scaffold.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.stereotype.Component;

/**
 * @author xiong.bo
 * @version 1.0
 * @date 2025/3/23 10:05 下午
 */

@Component
public class CustomOAuth2AccessDeniedHandler extends OAuth2AccessDeniedHandler {

  @Override
  public void handle(HttpServletRequest request, HttpServletResponse response,
      AccessDeniedException authException) throws IOException, ServletException {
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    response.setStatus(HttpStatus.FORBIDDEN.value());

    // 自定义返回格式

    Result result = Result.error(
        HttpStatus.UNAUTHORIZED.value(),
        "Forbidden: You do not have sufficient permissions to access this resource.",
        null
    );

    new ObjectMapper().writeValue(response.getOutputStream(), result);
  }
}
